package com.sise.aio和bio和nio.aio.基于aio的聊天室.test2;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author idea
 * @data 2019/1/22
 */
public class AIOServerHandle implements CompletionHandler<AsynchronousSocketChannel, AIOServer> {

    /**
     * 用于监听，当请求到来之后需要处理什么
     *
     * @param result
     * @param attachment
     */
    @Override
    public void completed(AsynchronousSocketChannel result, AIOServer attachment) {
        //这里的写法有点类似于递归，为下一次的请求做准备
        attachment.getServerSocketChannel().accept(attachment, this);
        doRead(result);
    }

    @Override
    public void failed(Throwable exc, AIOServer attachment) {
        exc.printStackTrace();
    }

    private void doRead(AsynchronousSocketChannel channel) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        /**
         * 这里面是一个异步的读操作，
         * ByteBuffer dst, 目的地，是处理客户端传递数据的一个中转操作
         * A attachment, 附属，发送数据，通常使用buffer处理
         * CompletionHandler<Integer,? super A> handler 处理器
         */
        channel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                System.out.println("处理完毕！");
                attachment.flip();
                System.out.println("content is："+new String(attachment.array(),0,attachment.limit()));
                //接下来部分交给控制台进行内容输入测试
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                exc.printStackTrace();
            }
        });
    }
}
